// 封装购物车模块
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { useUserStore } from './userStore'
import { cartListAPI, insertCartAPI, delCartAPI } from '@/apis/cart'

export const useCartStore = defineStore('cart', () => {
  const userStore = useUserStore()
  const isLogin = computed(() => userStore.userInfo.token)

  const cartList = ref([])

  // 获取购物车列表
  const getCartList = async () => {
    const res = await cartListAPI()
    cartList.value = res.result
  }

  // 添加购物车操作
  const addCart = async (goods) => {
    const { skuId, count } = goods
    if (isLogin.value) {
      await insertCartAPI({ skuId, count })
      await getCartList()
    } else {
      // 已添加过 - count + 1
      // 没有添加过 - 直接push
      // 思路：通过匹配传递过来的商品对象中的skuId能不能在cartList中找到，找到了就是添加过
      const item = cartList.value.find(item => goods.skuId === item.skuId)
      if (item) {
        item.count++
      } else {
        cartList.value.push(goods)
      }
    }
  }

  // 删除购物车
  const delCart = async (skuId) => {
    if (isLogin.value) {
      await delCartAPI([skuId])
      await getCartList()
    } else {
      // 思路：
      // 1. 找到要删除项的下标值 - splice
      // 2. 使用数组的过滤方法 - filter
      const idx = cartList.value.findIndex((item) => skuId === item.skuId)
      cartList.value.splice(idx, 1)
    }
  }

  // 清空购物车
  const clearCart = async () => {
    cartList.value = []
  }

  // 购物车单选
  const singleCheck = (skuId, selected) => {
    const item = cartList.value.find((item) => skuId === item.skuId)
    item.selected = selected
  }

  // 购物车全选
  const allCheck = (selected) => {
    cartList.value.forEach(item => item.selected = selected)
  }

  // 购物车总数量
  const allCount =  computed(() => {
    return cartList.value.reduce((acc, item) => {
      return acc + item.count
    }, 0)
  })

  // 购物车总金额
  const allPrice =  computed(() => {
    return cartList.value.reduce((acc, item) => {
      return acc + item.count * item.price
    }, 0)
  })

  // 购物车是否全选
  const isAll = computed(() => {
    return cartList.value.every((item) => item.selected)
  })

  // 购物车已勾选数量
  const selectedCount = computed(() => cartList.value.filter(item => item.selected).reduce((acc, item) => acc + item.count, 0))
  // 购物车已勾选数量的总金额
  const selectedPrice = computed(() => cartList.value.filter(item => item.selected).reduce((acc, item) => acc + item.count * item.price, 0))

  return {
    cartList,
    allCount,
    allPrice,
    isAll,
    selectedCount,
    selectedPrice,
    addCart,
    delCart,
    clearCart,
    singleCheck,
    allCheck,
    getCartList
  }
}, {
  persist: true,
})